package org.example.admin.zm;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.util.AliyunOSSUtil;
import org.springframework.web.bind.annotation.*;
import org.example.admin.entity.Dish;
import org.example.admin.service.DishService;
import org.example.util.R; // 假设R是统一响应对象
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.mock.web.MockMultipartFile;
import java.nio.file.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.UUID;

@RestController
@RequestMapping("/dish")
public class DishController {

    @Resource
    private DishService dishService;





    @GetMapping("/test")
    public String test() {
        Path basePath = Paths.get("D:", "Pro5_new", "srcfor", "archive", "chinese-food-175");
        StringBuilder resultLog = new StringBuilder();
        int successCount = 0;
        int failCount = 0;

        try (BufferedReader reader = Files.newBufferedReader(basePath.resolve("labels.txt"), StandardCharsets.UTF_8)) {
            String dishName;
            while ((dishName = reader.readLine()) != null) {
                // 1. 特殊字符处理（关键修复）
                String cleanDishName = dishName.replace("ZWNBSP", "") // 移除显式ZWNBSP字符串
                        .replace("\uFEFF", "") // 移除零宽度非断开空格
                        .replaceAll("\\p{C}", ""); // 移除所有控制字符

                try {
                    // 2. 验证菜品目录和图片
                    Path dishDir = basePath.resolve(cleanDishName);
                    if (!Files.exists(dishDir)) {
                        resultLog.append("目录不存在: ").append(dishDir).append("\n");
                        failCount++;
                        continue;
                    }

                    Path imagePath = dishDir.resolve("1.jpg");
                    if (!Files.exists(imagePath)) {
                        resultLog.append("图片不存在: ").append(imagePath).append("\n");
                        failCount++;
                        continue;
                    }

                    // 3. 上传OSS（添加上传超时机制）
                    String uuidFileName = generateUUIDFileName(imagePath);
                    MultipartFile multipartFile = convertToMultipartFile(imagePath, uuidFileName);

                    // 4. 添加1秒等待时间（解决图片中的超时问题）
                    try {
                        System.out.println("开始上传: " + cleanDishName);
                        String imageUrl = AliyunOSSUtil.upLoad(multipartFile);
                        // 上传成功等待1秒
                        Thread.sleep(1000); // 关键修改：每上传一张图片等待1秒

                        // 5. 创建菜品对象
                        Dish dish = new Dish();
                        dish.setDishcover(imageUrl);
                        dish.setDishname(cleanDishName);
                        dish.setDishprice(generateRandomPrice());
                        dish.setDishdescribe("好吃");
                        dish.setStoreid(generateRandomStoreId());
                        dish.setDishdiff(generateRandomDishDiff());

                        // 6. 插入数据库
                        int result = dishService.addDish(dish);
                        if (result > 0) {
                            successCount++;
                        } else {
                            resultLog.append("数据库插入失败: ").append(cleanDishName).append("\n");
                            failCount++;
                        }

                    } catch (OSSException | ClientException | InterruptedException e) {
                        // 处理OSS上传失败（含超时）和中断异常
                        resultLog.append("上传失败: ").append(cleanDishName)
                                .append(" - ").append(e.getClass().getSimpleName())
                                .append(": ").append(e.getMessage()).append("\n");
                        failCount++;
                    }

                } catch (IOException e) {
                    resultLog.append("IO错误: ").append(cleanDishName).append(" - ").append(e.getMessage()).append("\n");
                    failCount++;
                }
            }
        } catch (IOException e) {
            return "labels.txt读取失败: " + e.getMessage();
        }

        return String.format("批量导入完成！成功: %d, 失败: %d。详情:\n%s", successCount, failCount, resultLog);
    }



    // 使用Path重构辅助方法
    private String generateUUIDFileName(Path filePath) {
        String originalName = filePath.getFileName().toString();
        String extension = originalName.substring(originalName.lastIndexOf("."));
        return UUID.randomUUID().toString().replace("-", "") + extension;
    }

    // 辅助方法：File转MultipartFile
    private MultipartFile convertToMultipartFile(Path filePath, String fileName) throws IOException {
        return new MockMultipartFile(
                fileName,
                fileName,
                Files.probeContentType(filePath), // 自动检测MIME类型
                Files.readAllBytes(filePath)       // 直接读取字节数据
        );
    }

    // 辅助方法：生成随机价格(1-100)
    private int generateRandomPrice() {
        return new Random().nextInt(100) + 1;
    }

    // 辅助方法：随机选择店铺ID(1或2)
    private int generateRandomStoreId() {
        return new Random().nextBoolean() ? 1 : 2;
    }

    // 辅助方法：随机选择菜品类型(荤/素)
    private String generateRandomDishDiff() {
        return new Random().nextBoolean() ? "荤" : "素";
    }






    /**
     * 演示上传文件到OSS
     */
    @PostMapping("/upload")
    public R upload(MultipartFile file){
        String filePath = AliyunOSSUtil.upLoad(file);
        return R.ok(filePath);
    }
    /**
     * 分页搜索菜品
     * @param pageNum 页码
     * @param pageSize 每页数量
     *
     */
    @GetMapping("/search")
    public R search(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer storeId) {
        PageInfo<Dish> pageInfo = dishService.searchDishByName(
                pageNum, pageSize, keyword, storeId);
        return R.ok(pageInfo);
    }

    /**
     * 分页查询菜品列表
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @return 分页结果[1,6](@ref)
     */
    @GetMapping("/list")
    public R listDishes(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = true) Integer storeid) {
        PageHelper.startPage(pageNum, pageSize);
        List<Dish> dishes = dishService.selectByStoreId(Long.valueOf(storeid));
        PageInfo<Dish> pageInfo = new PageInfo<>(dishes);
        return R.ok(pageInfo);
    }

    /**
     * 根据ID查询菜品详情
     * @param dishId 菜品ID
     * @return 菜品详情[4](@ref)
     */
    @GetMapping("/detail")
    public R getDishDetail(@RequestParam Long dishId) {
        Dish dish = dishService.selectById(dishId);
        return dish != null ? R.ok(dish) : R.fail("菜品不存在");
    }

    /**
     * 新增菜品（含图片上传逻辑）
     * @param dish 菜品实体
     * @return 操作结果[3,4](@ref)
     */
    @PostMapping("/add")
    public R addDish(@RequestBody Dish dish) {
        int result = dishService.addDish(dish);
        return result > 0 ? R.ok("添加成功") : R.fail("添加失败");
    }

    /**
     * 更新菜品信息
     * @param dish 菜品实体（需包含ID）
     * @return 操作结果[7](@ref)
     */
    @PostMapping("/update")
    public R updateDish(@RequestBody Dish dish) {
        int result = dishService.updateDish(dish);
        return result > 0 ? R.ok("更新成功") : R.fail("更新失败");
    }

    /**
     * 删除菜品（支持批量删除）
     * @param dishId 菜品ID
     * @return 操作结果[1](@ref)
     */
    @DeleteMapping("/delete")
    public R deleteDish(@RequestParam Long dishId) {
        int result = dishService.deleteDish(dishId);
        return result > 0 ? R.ok("删除成功") : R.fail("删除失败");
    }
}
